package com.xjnt.frameworks.plugin.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import com.jfinal.log.Logger;

public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {
	
	private static final Logger log = Logger.getLogger(ShiroFormAuthenticationFilter.class);
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		// TODO 重写FormAuthenticationFilter onAccessDenied 方法，解决AJAX访问Session失效时的判定.
		if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                if (log.isDebugEnabled()) {
                    log.debug("Login submission detected.  Attempting to execute login.");
                }
                return executeLogin(request, response);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Login page view.");
                }
                //allow them to see the login page ;)
                return true;
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Attempting to access a path which requires authentication.  Forwarding to the " +
                        "Authentication url [" + getLoginUrl() + "]");
            }
            if(isAjax(WebUtils.toHttp(request))){
            	HttpServletResponse res = WebUtils.toHttp(response);
            	res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            } else {
            	saveRequestAndRedirectToLogin(request, response);
            }
//            saveRequestAndRedirectToLogin(request, response);
            return false;
        }
	}
	
	private boolean isAjax(HttpServletRequest request){
		String requestType = request.getHeader("X-Requested-With");
		return requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest");
	}
}
